version 13
clear all
clear matrix
set more off
set maxvar 3000
set matsize 2000

local path_load 	= "00_data/01_datasets/00_inputs"
local path_save 	= "00_data/01_datasets/01_results"
local path_output 	= "00_data/02_output"


*-------------------------------------------------------------------------------------------------------------------------------
* SET OPTIONS
*-------------------------------------------------------------------------------------------------------------------------------
local DepVar_Vector      = "EMBI_ARG_Change Merval_Change"  // LHS variable
local Controls_Variables = "dlnVIX dlnSP  dlnEEM"           // Global Control Variables
local Years_Sample       = "2007 2010"                      // Sample periods (2007 baseline; 2010 post misreport period)
local BETA_BOOT  = 1              							// Set=1 to compute Bootstrap CI for IV regressions
local BootsRep   = 2000          							// Number of Bootstrap Iterations (only relevant if BETA_BOOT==1)
local do_VarTest = 1                                        // Set=1 to compute test of identifying assumption 
local Plots      = 1                                        // Set=1 to plot the figures
*-------------------------------------------------------------------------------------------------------------------------------
*-------------------------------------------------------------------------------------------------------------------------------

* ------------------------------------------------------------------------------------------------
* Program to compute the rel variance of the BE inflation
* ------------------------------------------------------------------------------------------------
 program myratio, rclass
          summarize BE_Change if in_window==1
          local sd_in = r(sd)
          summarize BE_Change if out_window==1
          local sd_out = r(sd)
          return scalar ratio = `sd_in'/`sd_out'
 end
* ------------------------------------------------------------------------------------------------


foreach DepVar in `DepVar_Vector'     {   // Loop for LHS variable
foreach sample_year in `Years_Sample' {   // Loop for sample years
forval window_type =0/3               {   // Loop for different event windows (0 is the baseline 2-day window)

	*** Load dataset
	   global window_type = `window_type'
	   use "`path_load'/03_BreakEvenInflation.dta", clear
	   qui sort Date
	   qui gen date_id = _n
	   qui sort date_id
	   qui tset date_id

	*** Change in the BE rate
	    qui gen BE_Change   = (BE-L.BE)
	    qui label variable BE_Change "BE Change, pp"

	***	Log-variation in Argentine EMBI
		qui gen EMBI_ARG_Change   = 100*(ln(EMBI_ARG)-ln(L.EMBI_ARG))
		qui label variable EMBI_ARG_Change "EMBI % Change, pp"
		
	***	Log-variation in Argentine Stock Index (Merval)
		qui gen Merval_Change   = 100*(ln(Merval_px)-ln(L.Merval_px))
		qui label variable Merval_Change "Merval % Change, pp"

	** Define the LHS variable (ARG EMBI or Merval)
		if "`DepVar'" == "EMBI_ARG_Change" {
		qui gen DepVar_Change = EMBI_ARG_Change
		}
		else if "`DepVar'" == "Merval_Change" {
		qui gen DepVar_Change = Merval_Change
		}

	*** Merge with global controls dataset
		qui merge 1:1 Date using "`path_load'/01_GlobalFactors_Controls.dta"
		qui keep if _merge==3
		qui drop _merge
		qui sort date_id

	*** Compute % changes for the global factors
		foreach ii in "VIX_CLOSE" "SP_CLOSE" "EEM_CLOSE"{
		qui gen dln`ii' = 100*(`ii'-L.`ii')/L.`ii'
		qui replace  dln`ii' = . if  dln`ii'==0
		qui replace  dln`ii' = . if  dln`ii'>20
		qui replace  dln`ii' = . if  dln`ii'<-20
		}
		qui rename dlnVIX_CLOSE dlnVIX
		qui rename dlnSP_CLOSE dlnSP
		qui rename dlnEEM_CLOSE dlnEEM

	*** Keep sample period
	if `sample_year' == 2007 {
		qui keep if (Date>=d(01jan2007)  & Date<=d(01mar2008))
	}
	if `sample_year' == 2010 {
		qui keep if (Date>=d(01jan2010)  & Date<=d(01mar2011))
	}

	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// CREATE EVENT WINDOWS
	do "01_codes/00_CreateWindows_fx.do"
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


if `Plots'==1 & "`DepVar'" == "EMBI_ARG_Change" & `sample_year' == 2007 & `window_type'==0 {
	* --------------------------------------------------------------------------------  
	* SCATTER PLOT: SP & BE
	* --------------------------------------------------------------------------------
	
	* Compute the EMBI_ARG_Change residual, after controlling for global factors
	qui reg EMBI_ARG_Change `Controls_Variables', robust
	qui predict EMBI_ARG_Change_res, residuals

	* Regression between BE_Change and EMBI residual (only for the event window)
	reg EMBI_ARG_Change_res BE_Change if in_window==1, robust
	qui local beta     = round(_b[BE_Change],.001)
	if abs(`beta')<1 {
		qui local beta =  "0"+"`beta'"
	}
	qui matrix var_tmp = e(V)
	qui local se_tmp   = sqrt(var_tmp[1,1])
	qui local pval     = round((2 * ttail(e(N)-2, abs(`beta'/`se_tmp'))),.001) //two-sided p-val
	qui local pval     = "0"+"`pval'"
	qui twoway (scatter  EMBI_ARG_Change_res BE_Change if out_window==1, msize(vsmall) ) ///
	(scatter  EMBI_ARG_Change_res BE_Change if in_window==1, yline(0, lc(gs1) lpattern(dash) lwidth(vthin)) xline(0, lc(gs1) lpattern(dash) lwidth(vthin)) ///
	ytitle("Sov Spread (residual), % Change",  size(small) axis(1)) xtitle("BE Change (in pp)",  size(small) axis(1)) graphregion(color(white)) plotregion(color(white)) ) ///
	(lfit     EMBI_ARG_Change_res BE_Change if in_window==1, lcolor(black) lpattern(solid) text(-3.5 0.72 "beta=`beta'", place(e) size(small))  text(-4.2 0.72 "p-val=`pval'", place(e) size(small))   ylabel(, nogrid labsize(small))) , ///
	leg( order(2 "Events" 1 "Non-Events")  size(small) rows(2)   pos(2) ring(0)  nobox region(color(white)))
	graph export "03_figures_tables/01_Main/Scatter_BE_residSP_Window_0_Year_2007.pdf", replace 

	* --------------------------------------------------------------------------------  
	* Summary Statistics: Events vs Non-Events
	* --------------------------------------------------------------------------------
	preserve
		qui gen month = month(Date)
		qui gen year = year(Date)
		qui gen mdate = ym(year, month)
		format mdate %tm

		qui correlate EMBI_ARG_Change_res BE_Change if in_window==1, covariance
		local cov_EMBI_BE_event = r(cov_12)

		qui correlate EMBI_ARG_Change_res BE_Change if out_window==1, covariance
		local cov_EMBI_BE_nonevent = r(cov_12)

		* Generate auxiliary variables (to use in the collapse function below)
		qui gen EMBI_ARG_Change_mean    = EMBI_ARG_Change_res
		qui gen EMBI_ARG_Change_sd      = EMBI_ARG_Change_res 
		qui gen BE_Change_mean          = BE_Change
		qui gen BE_Change_sd            = BE_Change 
		qui gen cov_aux                 = .
		qui replace cov_aux             = `cov_EMBI_BE_event'      if in_window==1
		qui replace cov_aux             = `cov_EMBI_BE_nonevent'   if in_window==0
		qui gen days_counter            = 0
		qui replace days_counter        = 1 if (EMBI_ARG_Change_res!=. & BE_Change!=.)
		*Collapse: Compute mean & SD by event window
		qui collapse (mean) EMBI_ARG_Change_mean BE_Change_mean cov_aux (sd) EMBI_ARG_Change_sd  BE_Change_sd (sum) days_counter, by(in_window)
		order in_window EMBI_ARG_Change_mean BE_Change_mean  EMBI_ARG_Change_sd BE_Change_sd cov_aux days_counter

		*Write table
			qui gen event_counter = ceil(days_counter/2)
			qui file open table_SummaryStats using "03_figures_tables/01_Main/SummaryStats_Window_0_Year_2007.tex", write replace
			qui file write table_SummaryStats "\renewcommand{\arraystretch}{1.0}"
			qui file write table_SummaryStats "\begin{tabular}{lcc}" _n "\hline \hline" _n
			qui file write table_SummaryStats "Moments & Non-Event & Event \\" _n
			qui file write table_SummaryStats "\cline{1-3}" _n
			qui file write table_SummaryStats "\hline \hline" _n
			qui file write table_SummaryStats "Mean $\Delta ln(SP)$"   "&" (string(EMBI_ARG_Change_mean[1], "%5.3f")) "&" (string(EMBI_ARG_Change_mean[2], "%5.3f"))  " \\" _n
			qui file write table_SummaryStats "SD $\Delta ln(SP)$" 	   "&" (string(EMBI_ARG_Change_sd[1], "%5.3f"))   "&" (string(EMBI_ARG_Change_sd[2], "%5.3f"))    " \\" _n
			qui file write table_SummaryStats "Mean $\Delta BE$"       "&" (string(BE_Change_mean[1], "%5.3f"))       "&" (string(BE_Change_mean[2], "%5.3f"))        "\\"  _n
			qui file write table_SummaryStats "SD $\Delta BE$"         "&" (string(BE_Change_sd[1], "%5.3f"))         "&" (string(BE_Change_sd[2], "%5.3f"))   	      "\\"  _n
			qui file write table_SummaryStats "Cov($\Delta ln(SP)$,$\Delta BE$)" 		"&" (string(cov_aux[1], "%5.3f"))              "&" (string(cov_aux[2], "%5.3f"))        	   "\\"  _n
			qui file write table_SummaryStats "Observations"   	"&" (string(days_counter[1], "%5.0f"))         "&" (string(days_counter[2], "%5.0f"))   	   "\\"  _n
			qui file write table_SummaryStats "\hline \hline" _n
			qui file write table_SummaryStats "\end{tabular}" _n
			qui file close table_SummaryStats
			
			*Manually compute the extimators 
			gen estHAT   = round( (cov_aux[2]-cov_aux[1]) / (BE_Change_sd[2]^2-BE_Change_sd[1]^2)  ,0.01)
			gen estTILDE = round( (EMBI_ARG_Change_sd[2]^2-EMBI_ARG_Change_sd[1]^2) / (cov_aux[2]-cov_aux[1])  ,0.01)
			format estHAT %3.2f
			format estTILDE  %3.2f
			local estHAT    =  estHAT[1]
			local estTILDE  =  estTILDE[1]
			di `estHAT'
			di `estTILDE'
			qui file open   estHAT using "03_figures_tables/01_Main/Estimator_HAT.txt", write replace
			qui file write  estHAT  (string(estHAT[1], "%5.2f"))
			qui file close  estHAT
			qui file open   estTILDE using "03_figures_tables/01_Main/Estimator_TILDE.txt", write replace
			qui file write  estTILDE (string(estTILDE[1], "%5.2f"))
			qui file close  estTILDE
			save "`path_save'/ManualEstimators.dta", replace
			
	 restore
}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TEST OF VARIANCES FOR THE BE RATE (Events vs Non-event days)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	if `do_VarTest'==1{
	if "`DepVar'" == "EMBI_ARG_Change" & (`sample_year' == 2007 | `sample_year' == 2010)   {

		* Create matrix to store the results for the variance tests
	  	qui matrix VarianceTest     = J(11,1,.)

	  	* TEST 1: Standard F-test
	    sdtest BE_Change_in_window == BE_Change_out_window
			qui matrix VarianceTest[1,1]= r(p_u)     // upper one side p-value Prob(F>f): Ha: Ratio>1
			qui matrix VarianceTest[2,1]= r(F)       // F-statistic
			qui matrix VarianceTest[3,1]= r(sd)      // Sd for the entire sample
			qui matrix VarianceTest[4,1]= r(sd_1)    // Sd for the event days
			qui matrix VarianceTest[5,1]= r(sd_2)    // Sd for the non-event days
			qui matrix VarianceTest[6,1]= r(N)       // Total number of observations
		
		* TEST 2: Bootstrap - biased corrected
		* Note: Level is for the 2-sided CI. We assume symmetry
		foreach level_ci of numlist 80 90 {
			qui bootstrap r(ratio),  strata(in_window out_window)    seed(10) reps(`BootsRep') level(`level_ci') : myratio 
			qui estat bootstrap , all
			qui matrix ci_boot_`level_ci' = e(ci_bc)
		}
			qui matrix VarianceTest[8,1] = ci_boot_80[1,1]      // Bias-corrected CI (lower bound) - 80% two-sided (90% one-sided)
			qui matrix VarianceTest[9,1] = ci_boot_90[2,1]      // Bias-corrected CI (upper bound) - 80% two-sided (90% one-sided)
			qui matrix VarianceTest[10,1]= ci_boot_90[1,1]      // Bias-corrected CI (lower bound) - 90% two-sided (95% one-sided)
			qui matrix VarianceTest[11,1]= ci_boot_90[2,1]      // Bias-corrected CI (upper bound) - 90% two-sided (95% one-sided)

		* Store results in a .dta file
		preserve
			qui svmat  double VarianceTest, name(VarianceTest)
			qui keep VarianceTest
			qui keep if _n<=11
			qui gen Labels = ""
			qui replace Labels = "One sided p-val"        			 if _n==1
			qui replace Labels = "F-stat"                 			 if _n==2
			qui replace Labels = "SD(BE) - Entire Sample" 			 if _n==3
			qui replace Labels = "SD(BE) - Events"        			 if _n==4
			qui replace Labels = "SD(BE) - Non Events"    			 if _n==5
			qui replace Labels = "Observations"                      if _n==6
			qui replace Labels = "Bootstrap CI - Bias Corrected"     if _n==7
			qui replace Labels = "Bootstrap CI - Lower Bound  (90)"  if _n==8
			qui replace Labels = "Bootstrap CI - Upper Bound  (90)"  if _n==9
			qui replace Labels = "Bootstrap CI - Lower Bound  (95)"  if _n==10
			qui replace Labels = "Bootstrap CI - Upper Bound  (95)"  if _n==11
			qui save "`path_save'/10_VarianceTest_Window_`window_type'_Year_`sample_year'.dta", replace
	    restore
	}
	}
	//-----------------------------------------------------------------------------------------


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*Rigobon and Sack Estimator: IV APPROACH
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	if `sample_year' == 2007  {
	 
		//-----------------------------------------------------------------------------------------
		// GENERATE INSTRUMENTS TO RUN IV
		//-----------------------------------------------------------------------------------------
			qui gen     inst_hat = .
			qui replace inst_hat =    BE_Change          if  (in_window  == 1)
			qui replace inst_hat = -1*BE_Change          if  (out_window == 1)

		//-----------------------------------------------------------------------------------------
		// ADJUST INSTRUMENTS AND VARIABLES FOR DIFFERENT NUMBER OF OBS
		//-----------------------------------------------------------------------------------------
			local VAR_LIST = "inst_hat  EMBI_ARG_Change  Merval_Change DepVar_Change    BE_Change    dlnVIX dlnSP  dlnEEM"
			 qui foreach VAR of local VAR_LIST {
			 qui replace `VAR' = `VAR' / sqrt(days_event)     if in_window==1
			 qui replace `VAR' = `VAR' / sqrt(days_non_event) if out_window==1
			}
		    save tmp0_IV.dta,replace // Save full dataset (for bootstrap)
	
		//------------------------------------------------------------------------------	
		// IV REGRESSION:
		//------------------------------------------------------------------------------

		matrix Sample_IV      = J(1,5,.)   
		ivregress 2sls DepVar_Change  `Controls_Variables'  (BE_Change = inst_hat ) , robust
			qui matrix aa1    = e(V)
			qui scalar se_tmp = sqrt(aa1[1,1])
			qui matrix Sample_IV[1,1] = _b[BE_Change]                                // beta
			qui matrix Sample_IV[1,2] = se_tmp                 	                     // standard error
			qui matrix Sample_IV[1,3] = (_b[BE_Change]/se_tmp) 			             // t-stat
	        qui matrix Sample_IV[1,4] = (2 * ttail(e(N), abs(_b[BE_Change]/se_tmp))) // two-sided p-val
		 	qui matrix Sample_IV[1,5] = e(N)                                         // number of observations

		* Store results in a .dta file
		preserve
			clear
		    svmat  double Sample_IV, name(var)
			rename var1 beta
			rename var2 se
			rename var3 tstat
			rename var4 pval
			rename var5 obs
			gen Instrument = ""
			replace Instrument = "CIV Instruments" if 2==2
			order Instrument, first
		    save "`path_save'/20_IVReg_`DepVar'_Window_`window_type'.dta", replace
			*Save result for Julia input
			if "`DepVar'" == "EMBI_ARG_Change" & `sample_year' == 2007 & `window_type'==0 {
			qui file open   estHAT  using "`path_output'/Estimator_HAT_IV.txt", write replace
			qui file write  estHAT  (string(beta, "%5.2f"))
			qui file close  estHAT
			}
		restore
		//------------------------------------------------------------------------------

		*-------------------------------------------
		// Bootstrap repetition for IV regression
		*-------------------------------------------
		if `BETA_BOOT' ==1 { 

			set seed 10
			matrix Bootstrap_IV      = J(`BootsRep',5,.)   

			forvalues i= 1(1)`BootsRep' { 
				use "tmp0_IV.dta", clear                // Load dataset adjusted by sizes of windows

				preserve
					qui keep if in_window==1
					qui bsample days_event              // Resampling with replacement from event window. Number of observations = days_event
					qui save "tmp1.dta", replace        // Save bootstrap dataset for event window days
					restore
					preserve
					qui keep if out_window==1
					qui bsample days_non_event          // Resampling with replacement from outside event window.  Number of observations = non_event days
					qui save "tmp2.dta",replace         // Save bootstrap dataset for non-event window days
				restore

				use "tmp2.dta",clear
				qui append using tmp1

			    * Keep only those bootstrap samples in which the identification assumption holds
				qui sdtest BE_Change_in_window == BE_Change_out_window
				local ID_Assumption= r(p_u)
					if `ID_Assumption'<0.005  { 
						qui ivregress 2sls DepVar_Change  `Controls_Variables' (BE_Change = inst_hat ) , robust
						qui matrix aa1    = e(V)
						qui scalar se_tmp = sqrt(aa1[1,1])
						qui matrix Bootstrap_IV[`i',1] = _b[BE_Change]                                 // beta
						qui matrix Bootstrap_IV[`i',2] = se_tmp                 	                   // standard error
						qui matrix Bootstrap_IV[`i',3] = (_b[BE_Change]/se_tmp) 			           // t-stat
						qui matrix Bootstrap_IV[`i',4] = (2 * ttail(e(N), abs(_b[BE_Change]/se_tmp)))  // two-sided p-val
						qui matrix Bootstrap_IV[`i',5] = e(N)                                          // number of Obs.
					}

			}

		    * Store results in a .dta file
			preserve
				clear
			    svmat  double Bootstrap_IV, name(var)
				rename var1 beta
				rename var2 se
				rename var3 tstat
				rename var4 pval
				rename var5 obs
				gen Instrument = ""
				replace Instrument = "CIV Instruments"
				gen Boot_id = _n
				order Instrument Boot_id, first
				*Mean of beta across simulations
				egen beta_mean = mean(beta)
				*Percentile Bootstrap CI
				*1% CI
				egen p_005 = pctile(beta), p(0.5)
				egen p_995 = pctile(beta), p(99.5)
				*5% CI
				egen p_025 = pctile(beta), p(2.5)
				egen p_975 = pctile(beta), p(97.5)
				*10% CI
				egen p_050 = pctile(beta), p(5)
				egen p_950 = pctile(beta), p(95)
				*STORE RESULTS
			    save "`path_save'/20_Bootstrap_`DepVar'_Window_`window_type'.dta", replace
			restore
			erase  tmp1.dta
			erase  tmp2.dta
			
	} // Closes the Bootstrap conditional
    erase  tmp0_IV.dta
	} // closes conditional on sample year 2007
	

} // closes loop on window type
} // closes loop on year
} // closes loop on DepVar
